import { DeleteOutlined } from '@ant-design/icons';
import { Button, message } from 'antd';
import moment, { Moment } from 'moment';
import * as React from 'react';
import TimeRangePicker from './TimeRangePicker';
import { v4 as uuidv4 } from 'uuid';

interface IProps {
  /**初始值 */
  timesArr: { start: string; end: string }[];
  callback: (timesArr: any) => void;
}

const AllowTimesList: React.FC<IProps> = ({ timesArr, callback }) => {
  /**
   * 添加执行时间段
   */
  const handleAdd = (): void => {
    // todo-有bug，删除再新增，数据更新，视图没有更新。子组件未更新
    const arr = [...timesArr].filter((item: any) => item && item);
    if (arr.length >= 3) {
      message.warning('最多可填写3个时间段');
      return;
    }
    arr.length < 3 && arr.push({ start: '', end: '' });
    console.log(arr, 'handleAdd=====');
    callback(arr);
  };

  /**
   * 执行时间段改变
   *
   * @param {number} key
   * @param {[Moment, Moment]} date
   */
  const handleChange = (key: number, date: [Moment, Moment]) => {
    const arr = [...timesArr];
    const val = {
      start: date[0] ? date[0].format('HH:mm') : '',
      end: date[1] ? date[1].format('HH:mm') : '',
    };
    arr[key] = val;
    console.log(arr, 'handleChange=====');
    callback(arr);
  };

  /**
   * 删除一个时间段
   */
  const handleDel = (index: number) => {
    console.log('删除时间', index);
    const arr = [...timesArr];
    delete arr[index];
    console.log(arr, 'handleDel=====');
    callback(arr);
  };

  if (!timesArr) {
    return null;
  }
  return (
    <>
      {timesArr.map((item: { start: string; end: string }, index: number) => {
        if (!item) {
          return null;
        }
        const s = item?.start ? moment(item.start, 'HH:mm') : null;
        const e = item?.end ? moment(item.end, 'HH:mm') : null;
        const arr: any = [s, e];
        const id = uuidv4();

        return (
          <div key={'item_' + id} className="allow-time-item">
            <TimeRangePicker
              key={'timerange_' + id}
              timeValue={arr}
              callbackfn={(val: [Moment, Moment]) => {
                handleChange(index, val);
              }}
            />
            {index ? (
              <DeleteOutlined
                className="btn-del-time"
                onClick={() => {
                  handleDel(index);
                }}
              />
            ) : (
              <Button
                type="primary"
                className="btn-add-time"
                onClick={() => {
                  handleAdd();
                }}
              >
                添加时间段
              </Button>
            )}
          </div>
        );
      })}
    </>
  );
};

export default AllowTimesList;
